package com.uduemc.biso.node.module.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.uduemc.biso.node.core.entities.HSSL;
import com.uduemc.biso.node.module.mapper.HSSLMapper;
import com.uduemc.biso.node.module.service.HSSLService;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class HSSLServiceImpl implements HSSLService {

	@Autowired
	private HSSLMapper hSSLMapper;


	@Override
	public HSSL create(Long hostId, Long domainId, long resourcePrivatekeyId, long resourceCertificateId, short httpsOnly) {
		HSSL hssl = new HSSL();
		hssl.setHostId(hostId).setDomainId(domainId).setResourcePrivatekeyId(resourcePrivatekeyId).setResourceCertificateId(resourceCertificateId)
				.setHttpsOnly(httpsOnly);
		return insert(hssl);
	}

	@Override
	public HSSL insert(HSSL hssl) {
		hSSLMapper.insertSelective(hssl);
		return findOne(hssl.getId());
	}

	@Override
	public HSSL findByHostDomainId(Long hostId, Long domainId) {
		Example example = new Example(HSSL.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("domainId", domainId);
		example.setOrderByClause("`id` DESC");

		HSSL hssl = null;
		List<HSSL> selectByExample = hSSLMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(selectByExample)) {
			return hssl;
		}

		hssl = selectByExample.get(0);
		return hssl;
	}

	@Override
	public HSSL findOne(Long id) {
		return hSSLMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<HSSL> findInfos(long hostId) {
		Example example = new Example(HSSL.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		example.setOrderByClause("`id` ASC");

		return hSSLMapper.selectByExample(example);
	}

	@Override
	public HSSL updateById(HSSL hssl) {
		hSSLMapper.updateByPrimaryKey(hssl);
		return findOne(hssl.getId());
	}

	@Override
	public HSSL deleteById(Long id) {
		HSSL hssl = findOne(id);
		if (hssl == null) {
			return null;
		}
		hSSLMapper.deleteByPrimaryKey(id);
		return hssl;
	}

	@Override
	public HSSL delete(Long hostId, Long domainId) {
		HSSL hssl = findByHostDomainId(hostId, domainId);
		if (hssl == null) {
			return null;
		}

		Example example = new Example(HSSL.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("hostId", hostId);
		criteria.andEqualTo("domainId", domainId);
		hSSLMapper.deleteByExample(example);
		return hssl;
	}

	@Override
	public List<HSSL> infosByRepertoryId(Long hostId, Long repertoryId) {
		List<HSSL> infosByRepertoryId = hSSLMapper.infosByRepertoryId(hostId, repertoryId);
		return infosByRepertoryId;
	}

	@Override
	public Integer queryBindSSLCount(int trial, int review) {
		return hSSLMapper.queryBindSSLCount(trial,review);
	}

}
